/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.workflowDesign.controller;

import com.koron.util.Tools;
import com.koron.workflow.common.annotation.CaseUser;
import com.koron.workflow.common.bean.StaffBean;
import com.koron.workflow.common.util.BusinessCode;
import com.koron.workflow.common.util.WorkflowUtil;
import com.koron.workflow.workflowDesign.bean.ProcessBean;
import com.koron.workflow.workflowDesign.service.ProcessService;
import com.koron.workflow.workflowDesign.service.WorkflowDesignService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author qingfeng
 * @description: TODO
 * @date 2020/4/7 14:27
 */
@Api(value = "WorkflowDesignController", description = "流程设计")
@RestController
public class WorkflowDesignController {
	
	private static final Logger logger = LoggerFactory.getLogger(WorkflowDesignService.class);
	
    @Autowired
    private WorkflowDesignService service;

    @Autowired
    private ProcessService processService;
    
    @Value("${superadministrator}")
    private String account;
    
    @Value("${token.expireTime}")
    private String expireTime;

    @GetMapping("/workFlowDesignSSO.htm")
    public ModelAndView workFlowDesignSSO(@RequestParam(required = true) String setCode, 
    									  @RequestParam(required = true) String appCode,
    		                              @RequestParam(required = true) String processCode, 
    		                              @RequestParam(required = true) String account, 
    		                              HttpServletRequest request,
    		                              HttpServletResponse response) throws UnsupportedEncodingException {
    	ModelAndView view = Tools.getView("map.btl");
    	try {
			StaffBean staff = WorkflowUtil.getStaffByAccount(account);
			if(staff == null) {
				logger.error("账号不存在：{}", account);
				view.setViewName("redirect:/errorMsg.html?errormsg="+URLEncoder.encode("账号不存在,请添加当前单点的账号!!!", "UTF-8"));
				return view;
			}
			WorkflowUtil.setTokenCookie(response, staff);
			logger.info("单点登录成功 当前用户：{}", staff.getName());
	        ProcessBean process = ADOConnection.runTask(processService,"getProcess",ProcessBean.class,appCode,setCode,processCode);
	        view.addObject("processId", process.getId());
	        view.addObject("name", process.getName());
	        String svg = ADOConnection.runTask(service,"getSvg",String.class, process.getId());
	        view.addObject("svg", svg.trim());
	        return view;
		}catch(Exception ex) {
			view.setViewName("redirect:/errorMsg.html?errormsg="+URLEncoder.encode("页面发生不可预知的错误!!!", "UTF-8"));
			return view;
		}
    }

    @GetMapping("/workFlowDesign.htm")
    @ApiOperation("流程设计界面")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appCode", value = "应用id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "setCode", value = "模板组id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "processCode", value = "编码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "流程模板名称", required = false, dataType = "String", paramType = "query"),
    })
    public ModelAndView workFlowDesign(@RequestParam(required = true) String appCode, 
    		                           @RequestParam(required = true) String setCode, 
    		                           @RequestParam(required = true) String processCode, 
    		                           @RequestParam(required = true) String name) {
        ModelAndView view = Tools.getView("map.btl");
        ProcessBean process = ADOConnection.runTask(processService,"getProcess",ProcessBean.class,appCode,setCode,processCode);
        view.addObject("processId", process.getId());
        view.addObject("name", process.getName());
        String svg = ADOConnection.runTask(service,"getSvg",String.class, process.getId());
        view.addObject("svg", svg.trim());
        return view;
    }

    @GetMapping("/updateWorkFlowCandidateSSO.htm")
    public ModelAndView updateWorkFlowCandidate(
    		@RequestParam(required = true) String appCode, 
    		@RequestParam(required = true) String setCode, 
    		@RequestParam(required = true) String processCode, 
    		@RequestParam(required = true) String account, 
            HttpServletRequest request,
            HttpServletResponse response) throws UnsupportedEncodingException {
    	ModelAndView view = Tools.getView("map1.btl");
    	try {
            StaffBean staff = WorkflowUtil.getStaffByAccount(account);
            if(staff == null) {
				logger.error("账号不存在：{}", account);
				view.setViewName("redirect:/errorMsg.html?errormsg="+URLEncoder.encode("账号不存在,请添加当前单点的账号!!!", "UTF-8"));
				return view;
			}
    		WorkflowUtil.setTokenCookie(response, staff);
    		logger.info("单点登录成功 当前用户：{}", staff.getName());
            ProcessBean process = ADOConnection.runTask(processService,"getProcess",ProcessBean.class,appCode,setCode,processCode);
            view.addObject("processId", process.getId());
            view.addObject("name", process.getName());
            String svg = ADOConnection.runTask(service,"getSvg",String.class, process.getId());
            view.addObject("svg", svg.trim());
            return view;
    	}catch(Exception ex) {
    		view.setViewName("redirect:/errorMsg.html?errormsg="+URLEncoder.encode("页面发生不可预知的错误!!!", "UTF-8"));
			return view;
    	}
    }

    /**
     * 工作流设计界面提交
     * @param svgString
     * @param design
     * @param name
     * @param processId
     * @param req
     * @return
     */
    @ApiOperation("流程图提交")
    @PostMapping(value = "/workFlowSubmit.htm")
    public String workFlowSubmit(@ApiIgnore @CaseUser StaffBean user,String svgString, String design, String name, String processId, HttpServletRequest req) {
        try {
            return ADOConnection.runTask(service,"workFlowSubmit",MessageBean.class, user, svgString,design,name,processId).toJson();
        }catch (Exception e) {
            logger.error("保存流程图失败",e);
            return MessageBean.create(BusinessCode.EXCEPTION.getCode(),"保存流程图失败",String.class).toJson();
        }
    }
    
    /**
     * 流程发布
     * @param id
     * @return
     */
    @ApiOperation("流程发布")
    @PostMapping(value = "/deploy.htm")
    public String deploy(@ApiIgnore @CaseUser StaffBean user, String id) {
        try {
        	if(StringUtils.isEmpty(id)) {
        		return MessageBean.create(BusinessCode.EXCEPTION.getCode(),"id 不能为空",String.class).toJson();
        	}
            return ADOConnection.runTask(service,"deploy", MessageBean.class, id).toJson();
        }catch (Exception e) {
            logger.error("流程发布失败",e);
            return MessageBean.create(BusinessCode.EXCEPTION.getCode(),"流程发布失败",String.class).toJson();
        }
    }

    @ApiOperation("验证子流程编码")
    @GetMapping(value = "/validateProcessCode.htm")
    public String validateProcessCode(String processCode) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), boolean.class);
        try {
            boolean flag =  ADOConnection.runTask(processService,"validateProcessCode",Boolean.class, processCode);
            msg.setData(flag);
            return msg.toJson();
        }catch (Exception e) {
            logger.error("验证失败",e);
            return MessageBean.create(BusinessCode.EXCEPTION.getCode(),"验证失败",String.class).toJson();
        }
    }
}
